package cn.jbt.api.admin.util;

import cn.jbt.api.admin.service.ISysConfigService;
import cn.jbt.common.util.ApplicationContextUtil;
import cn.jbt.config.AliyunOssConfig;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;

import java.io.ByteArrayInputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class AliyunOssUtil {

    public static Map<String, Object> uploadFile(byte[] file, String filename) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

        ApplicationContext context = ApplicationContextUtil.getContext();
        ISysConfigService iSysConfigService = context.getBean(ISysConfigService.class);

        AliyunOssConfig aliyunOss = (AliyunOssConfig) iSysConfigService.getConfig("AliyunOss");
        OSS ossClient = new OSSClientBuilder().build(aliyunOss.getEndpoint(),
                aliyunOss.getAccessKeyID(), aliyunOss.getAccessKeySecret());

        // 文件扩展名
        String filenameExt = filename.substring(filename.lastIndexOf(".") + 1);
        // 设置存储对象名称
        String objectName = sdf.format(new Date()) + "/" + filenameExt + "/" + filename;

        PutObjectResult putObjectResult = ossClient.putObject(aliyunOss.getBucket(), objectName, new ByteArrayInputStream(file));
        log.info("PutObjectResult: [{}]", putObjectResult);

        Map<String, Object> result = new HashMap<>();
        result.put("url", String.format("https://%s.%s/%s", aliyunOss.getBucket(), aliyunOss.getEndpoint(), objectName));
        return result;

    }

}
